<?php defined('SYSPATH') or die('No direct script access.');
/**
* Module Simple Products
*/
class Module_Products_Products {
	
	private $controller;
	private $ss;
	private $thesystems;
	private $myfunctions;
	private $mydatetime;
	private $message;
	private $arraylist;
	
	static function &factory() {
	   $o = new Module_Products_Products();
	  return $o;	
	}
	
	public function __construct()
	{
		$this->controller  = Request::current()->controller();
		$this->ss          = Session::instance();
		$this->thesystems  = Helper_theSystems::factory();
		$this->myfunctions = Helper_myFunctions::factory();
		$this->mydatetime  = Helper_MyDateTime::factory();
		$this->message     = Language_Message::factory();
		$this->arraylist   = Helper_ArrayList::factory();
	}
	
	public function showproducts($command, $id, $categories, $subcategories, $brands, $image_id)
	{
		$details_type     = $this->thesystems->system_auth('module_products_detail_type');
		$rpp              = $this->thesystems->get_config('cms', 'pagination_medium_view');  // Record per page
		$halaman          = Arr::get($_GET,'page',1);
		$offset           = ($halaman - 1)*$rpp;
		$check_multistore = $this->thesystems->system_auth('accounting_multistores');
		
		switch ($command)
		{
			
		case "search":
				// Search Products
				$this->ss->delete('kriteria');
				
				$prod_name        = Arr::get($_POST, 'name');
				$prod_code        = Arr::get($_POST, 'code');
				$prod_category    = Arr::get($_POST, 'prodcategories_id');
				$prod_brand       = Arr::get($_POST, 'prodbrands_id');
				$prod_barcode_pcs = Arr::get($_POST, 'barcode_pcs');
          		$this->ss->set('kriteria',$_POST);
				  break;
		
		case "viewall":
				  $this->ss->delete('kriteria');
				  $r = Request::current();
				  $r->redirect($this->controller.'/products');
				  break;
		
		case "product_create":
				  // Create New Product

					$check_prodcategories= DB::select('id','value')
							->from('prodcategories')
							->where('value','=',$_POST['prodcategories_id'])
							->execute()->as_array();
						if(!empty($check_prodcategories)) {
							$prodcategories_id = $check_prodcategories[0]['id'];
						} else {
						  $this->message->store_message('c_fails');
						  $r = Request::current();
						  $r->redirect('pos/products?a=1');
						}

					$check_prodbrands= DB::select('id','value')
							->from('prodbrands')
							->where('value','=',$_POST['prodbrands_id'])
							->execute()->as_array();
						if(!empty($check_prodbrands)) {
							$prodbrands_id = $check_prodbrands[0]['id'];
						} else {
						  $this->message->store_message('c_fails');
						  $r = Request::current();
						  $r->redirect('pos/products?a=2');
						}
					
					$accstores_id      = (!is_null($check_multistore) ? $this->ss->get('accstores_id') : NULL);
					$prodcategories_id = $prodcategories_id;
					$prodbrands_id     = $prodbrands_id;
					$approve           = Arr::get($_POST,('approve'));
					$code              = $_POST['code'];
					$barcode_pcs       = $_POST['barcode_pcs'];
					$barcode_karton    = $_POST['barcode_karton'];
					$barcode_box       = $_POST['barcode_box'];
					$barcode_bungkus   = $_POST['barcode_bungkus'];
					$barcode_sama      = Arr::get($_POST,'barcode_sama');
					$name              = $_POST['name'];
					
					$price_karton_1    = $_POST['price_karton_1'];
					$price_box_1       = $_POST['price_box_1'];
					$price_bungkus_1   = $_POST['price_bungkus_1'];
					$price_pcs_1       = $_POST['price_pcs_1'];
					
					$keuntungan        = $_POST['keuntungan'];
					$keuntungan_satuan = $_POST['keuntungan_satuan'];
					
					$price_karton_buy  = $_POST['price_karton_buy'];
					$price_box_buy     = $_POST['price_box_buy'];
					$price_bungkus_buy = $_POST['price_bungkus_buy'];
					$price_pcs_buy     = $_POST['price_pcs_buy'];
					

					$pcs_per_karton    = $_POST['pcs_per_karton'];
					$pcs_per_box       = $_POST['pcs_per_box'];
					$pcs_per_bungkus   = $_POST['pcs_per_bungkus'];
					$pecahan           = Arr::get($_POST,'pecahan');
					$sat_pcs         = $_POST['sat_pcs'];
					$limit             = $_POST['limit'];
				  
				  $description						= $_POST['description'];
				  
				  $query = DB::insert('products', array(
						'prodcategories_id',
						'prodbrands_id',
						'accstores_id',
						'approve',
						'price_karton_1',
						'price_box_1',
						'price_bungkus_1',
						'price_pcs_1',
						'price_karton_buy',
						'price_box_buy',
						'price_bungkus_buy',
						'keuntungan',
						'keuntungan_satuan',
						'price_pcs_buy',
						'pcs_per_karton',
						'pcs_per_box',
						'pcs_per_bungkus',
						'pecahan',
						'sat_pcs',
						'limit',
						'code',
						'barcode_pcs',
						'barcode_karton',
						'barcode_box',
						'barcode_bungkus',
						'barcode_sama',
						'description',
						'name'
						))
					  ->values(array(
							$prodcategories_id,
							$prodbrands_id,
							$accstores_id,
							$approve,
							$price_karton_1,
							$price_box_1,
							$price_bungkus_1,
							$price_pcs_1,
							$price_karton_buy,
							$price_box_buy,
							$price_bungkus_buy,
							$keuntungan,
							$keuntungan_satuan,
							$price_pcs_buy,
							$pcs_per_karton,
							$pcs_per_box,
							$pcs_per_bungkus,
							$pecahan,
							$sat_pcs,
							$limit,
							$code,
							$barcode_pcs,
							$barcode_karton,
							$barcode_box,
							$barcode_bungkus,
							$barcode_sama,
							$description,
							$name
							));
					$result = $query->execute();
					if ($result[1] == 1) {
						$this->message->store_message('c_success');
					  $r = Request::current();
					  $r->redirect($this->controller.'/products?id='.$result[0]);
					} else {
						$this->message->store_message('c_fails');
					}
					break;
		
		case "product_update":
				  // Update Product
					$p['accstores_id']      = (!is_null($check_multistore) ? $this->ss->get('accstores_id') : NULL);
					$p['approve']           = Arr::get($_POST,('approve'));
					$p['barcode_pcs']       = $_POST['barcode_pcs'];
					$p['barcode_karton']    = $_POST['barcode_karton'];
					$p['barcode_box']       = $_POST['barcode_box'];
					$p['barcode_bungkus']   = $_POST['barcode_bungkus'];
					$p['barcode_sama']      = Arr::get($_REQUEST,'barcode_sama');
					$p['name']              = $_POST['name'];
					$p['price_karton_1']    = $_POST['price_karton_1'];
					$p['price_box_1']       = $_POST['price_box_1'];
					$p['price_bungkus_1']   = $_POST['price_bungkus_1'];
					$p['price_pcs_1']       = $_POST['price_pcs_1'];
					$p['price_pcs_buy']     = $_POST['price_pcs_buy'];
					$p['price_bungkus_buy'] = $_POST['price_bungkus_buy'];
					$p['price_box_buy']     = $_POST['price_box_buy'];
					$p['price_karton_buy']  = $_POST['price_karton_buy'];
					$p['keuntungan']        = $_POST['keuntungan'];
					$p['keuntungan_satuan'] = $_POST['keuntungan_satuan'];
					$p['pcs_per_karton']    = $_POST['pcs_per_karton'];
					$p['pcs_per_box']       = $_POST['pcs_per_box'];
					$p['pcs_per_bungkus']   = $_POST['pcs_per_bungkus'];
					$p['pecahan']           = Arr::get($_POST,'pecahan');
					$p['sat_pcs']         	= $_POST['sat_pcs'];
					$p['limit']             = $_POST['limit'];
					$p['description']       = $_POST['description'];
				  
				  $query = DB::update('products')
					  ->set($p)
					  ->where('id', '=', $id);
				  $result = $query->execute();
					  if ($result == 1) {
							$this->message->store_message('u_success');
							$r = Request::current();
							$r->redirect($this->controller.'/products?id='.$id);
					  } else {
							$this->message->store_message('u_fails');
					  }
					break;
		
		case "product_delete":
				  // Delete Image Files
				  $deletefiles = DB::select()
					  ->from('prodimages')
					  ->where('products_id', '=', $id)
					  ->execute();
				  $deletefilesresults = $deletefiles->as_array();
				  
				  $dir = 'assets/global/products/';
				  
				  foreach($deletefilesresults as $deletefilesresult)
				  {
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'large')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'large'));
					  }
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'thumb')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'thumb'));
					  }
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'small')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'small'));
					  }
					}
				  
				  // Delete Image Data
				  $query = DB::delete('prodimages')
					  ->where('products_id', '=', $id)
						->execute();
					
					// Delete Product Data
				  $query = DB::delete('products')
					  ->where('id', '=', $id)
					  ->limit(1);
				  $result = $query->execute();
					  if ($result == 1) {
							$this->message->store_message('d_success');
							$r = Request::current();
							$r->redirect($this->controller.'/products');
					  } else {
							$this->message->store_message('d_fails');
					  }
					break;
		
		case "image_create":
				  // Create Image Data and Upload Image
				  $datetime	= $this->mydatetime->save_to_sql_datetime_now('datetime');
				  
				  // Upload Image
				  if($_FILES['filename']['error']==0)
				  {
					  $filename = Upload::save($_FILES['filename'],NULL,'assets/global/products/');
					  
						// Resize, and save the image as SMALL
					  Image::factory($filename)
						  ->resize(100, NULL)
						  ->save('assets/global/products/'.$this->myfunctions->set_filename(basename($filename),'small'));
						
					  // Check Width and Height of the Images
					  $imgheight	= Image::factory($filename)->height;
					  $imgwidth		= Image::factory($filename)->width;
					  
					  // Resize, and save the image (Check Landscape or Portrait)
					  if($imgheight < $imgwidth)
					  {
						  // For Landscape Photo
							// Resize, Crop, and save the image as THUMBNAIL
						  Image::factory($filename)
							  ->resize(220, NULL)
							  ->crop(200,200)
							  ->save('assets/global/products/'.$this->myfunctions->set_filename(basename($filename),'thumb'));
						  
							// Resize, and save the image as LARGE
							Image::factory($filename)
							  ->resize(600, NULL)
							  ->save('assets/global/products/'.$this->myfunctions->set_filename(basename($filename),'large'));
						  
					  } else {
						  // For Portrait Photo
							// Resize, Crop, and save the image as THUMBNAIL
						  Image::factory($filename)
							  ->resize(NULL, 220)
							  ->crop(200,200)
							  ->save('assets/global/products/'.$this->myfunctions->set_filename(basename($filename),'thumb'));
						  
							// Resize, and save the image as LARGE
							Image::factory($filename)
							  ->resize(NULL, 600)
							  ->save('assets/global/products/'.$this->myfunctions->set_filename(basename($filename),'large'));
					  }
				  } else {
						$this->message->store_message('upload_criteria_fails');
					  $r = Request::current();
					  $r->redirect($this->controller.'/products?id='.$id);
				  }
				  
				  // Insert Data
				  $query = DB::insert('prodimages', array('products_id','productskus_id','datetime','filename'))
				  ->values(array($id,NULL,$datetime,basename($filename)));
				  $result = $query->execute();
					  if ($result[1] == 1)
					  {
						  unlink('assets/global/products/'.basename($filename));
							
							$this->message->store_message('c_success');
						  $r = Request::current();
						  $r->redirect($this->controller.'/products?id='.$id);
					  } else {
							$this->message->store_message('c_fails');
					  }
					break;
		
		case "image_delete":
				  // Delete Image Files
				  $deletefiles = DB::select()
					  ->from('prodimages')
					  ->where('id', '=', $image_id)
					  ->execute();
				  $deletefilesresults = $deletefiles->as_array();
				  
				  $dir = 'assets/global/products/';
				  
				  foreach($deletefilesresults as $deletefilesresult)
				  {
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'large')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'large'));
					  }
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'thumb')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'thumb'));
					  }
					  if (file_exists($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'small')))
					  {
						  unlink($dir.$this->myfunctions->set_filename($deletefilesresult['filename'],'small'));
					  }
					}
				  
				  // Delete Image Data
				  $query = DB::delete('prodimages')
					  ->where('id', '=', $image_id)
					  ->limit(1);
				  $result = $query->execute();
					  if ($result == 1) {
							$this->message->store_message('d_success');
						  $r = Request::current();
						  $r->redirect($this->controller.'/products?id='.$id);
					  } else {
							$this->message->store_message('d_fails');
					  }
					break;
		
		}
		
		$kriteria         = $this->ss->get('kriteria');
		$prod_name        = Arr::get($this->ss->get('kriteria'), 'name');
		$prod_code        = Arr::get($this->ss->get('kriteria'), 'code');
		$prod_category    = Arr::get($this->ss->get('kriteria'), 'prodcategories_id');
		$prod_brand       = Arr::get($this->ss->get('kriteria'), 'prodbrands_id');
		$prod_barcode_pcs = Arr::get($this->ss->get('kriteria'), 'barcode_pcs');
		
		$all_items = DB::select()
			->from('products');
			
		if(!is_null($kriteria))
		{
			if(!empty($prod_name)) {
				$all_items = $all_items->where('name', 'LIKE', '%'.$prod_name.'%');
			}
			if(!empty($prod_code)) {
				$all_items = $all_items->where('code', 'LIKE', '%'.$prod_code.'%');
			}
			if(!empty($prod_category)) {
				$all_items = $all_items->where('prodcategories_id', '=', $prod_category);
			}
			if(!empty($prod_brand)) {
				$all_items = $all_items->where('prodbrands_id', '=', $prod_brand);
			}
			if(!empty($prod_barcode_pcs)) {
				$all_items = $all_items->where('barcode_pcs', '=', $prod_barcode_pcs);
			}
		}
		
		$all_items = $all_items->execute();
		$count = $all_items->count();
		
		$productlists = DB::select()
			->from('products')
			->limit($rpp)
			->offset($offset);
			
		if(!is_null($kriteria))
		{
			if(!empty($prod_name)) {
				$productlists = $productlists->where('name', 'LIKE', '%'.$prod_name.'%');
			}
			if(!empty($prod_code)) {
				$productlists = $productlists->where('code', 'LIKE', '%'.$prod_code.'%');
			}
			if(!empty($prod_category)) {
				$productlists = $productlists->where('prodcategories_id', '=', $prod_category);
			}
			if(!empty($prod_brand)) {
				$productlists = $productlists->where('prodbrands_id', '=', $prod_brand);
			}
			if(!empty($prod_barcode_pcs)) {
				$productlists = $productlists->where('barcode_pcs', '=', $prod_barcode_pcs);
			}
		}
			
		$productlists = $productlists->order_by('position', 'ASC')
			->order_by('name', 'ASC');
		$productlists = $productlists->execute();
		
		$productupdate = DB::select()
			->from('products')
			->where('id', '=', $id)
			->limit(1)
			->execute();
		
		$pagination = Helper_myFunctions::factory()->paginations($count,$rpp);
		
		$content['title']		= 'Products';
		$content['content']	= View::factory('inc/products')
			->set('productlists',$productlists)
			->set('productupdate',$productupdate[0])
			->set('pagination',$pagination)
			->render();
		
		return $content;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}